﻿
using Cache;
using Domain.Entity;
using DtoFw.Base;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.IO;
using Microsoft.AspNetCore.Http;
using System.Text;
using Service;
using Util;

namespace SceneEvidenceAPI.Filters
{
    /// <summary>
    /// 自定义特性异常抛出
    /// </summary>
    public class ActionFilter : IActionFilter, IResultFilter
    {
        private readonly MainHomeService rep_home;
        /// <summary>
        /// 服务器Mac地址
        /// </summary>
        private readonly string ServerMacAddress = "00-FF-94-DE-8B-6D";
        public ActionFilter(MainHomeService homeService)
        {
            this.rep_home = homeService;
        }
        /// <summary>
        /// action执行前
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            //string machCodeKey = "MACHCODE";
            //if (!GlobalData.Cache.Exists(machCodeKey))
            //{
            //    var macAddress = MacHelper.GetMacAddress();
            //    if (ServerMacAddress != macAddress)
            //    {
            //        throw new Exception("未授权的服务器");
            //    }
            //    else
            //    {
            //        GlobalData.Cache.Set(machCodeKey, macAddress, 60);
            //    }
            //}
            if (context.ActionDescriptor.AttributeRouteInfo.Template.Contains("api/common/"))
                return;
            if (!string.IsNullOrWhiteSpace(context.HttpContext.Request.Headers["Authorization"]))
            {
                string token = context.HttpContext.Request.Headers["Authorization"];
                if (!string.IsNullOrWhiteSpace(token))
                {
                    ClaimsPrincipal c = TokenHelper.GetPrincipalFromAccessToken(token.Split(" ")[1]);
                    foreach (var item in context.ActionArguments)
                    {
                        if(item.Value != null)
                        {
                            var Info = item.Value.GetType().GetProperties().FirstOrDefault(x => x.Name == "CurrentUser");
                            if (Info != null)
                            {
                                Info.SetValue(item.Value, TokenHelper.GetTokenInfo<TokenData>(c));
                            }
                        }
                    }
                }
            }
            //校验参数
            if (!context.ModelState.IsValid)
            {
                var errorMsg = context.ModelState.Values.SelectMany(e => e.Errors).Select(e => e.ErrorMessage).FirstOrDefault();
                context.Result = new OkObjectResult(new
                {
                    Code = 400,
                    Msg = string.IsNullOrWhiteSpace(errorMsg) ? "参数校验错误" : errorMsg,
                    Data = new { },
                });
                return;
            }
        }
        /// <summary>
        /// action执行后
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuted(ActionExecutedContext context)
        {

        }
        /// <summary>
        /// 响应前
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuted(ResultExecutedContext context)
        {
            MinLogEntity entity = new MinLogEntity();
            var request = context.HttpContext.Request;
            string control = context.RouteData.Values["Controller"].ToString();
            string aciton = context.RouteData.Values["Action"].ToString();
            if (!string.IsNullOrWhiteSpace(context.HttpContext.Request.Headers["Authorization"]))
            {
                string token = context.HttpContext.Request.Headers["Authorization"];
                ClaimsPrincipal c = TokenHelper.GetPrincipalFromAccessToken(
                    token.Split(" ")[1]);
                var tokenData = TokenHelper.GetTokenInfo<TokenData>(c);
                entity.CreateTime = DateTime.Now;
                entity.Creator = tokenData?.UserName;
                entity.CreatorId = tokenData?.UserId;
                entity.OrganId = tokenData?.OrganId ?? 0;
            }
            var body = GetContent(context);
            entity.Module = control;
            entity.Action = aciton;
            entity.RequestBody = body.Item1;
            entity.ResponseBody = body.Item2;
            entity.Method = request.Method;
            var list = rep_home.GetDics(CacheKey.Dic_ModuleDictionary);
            if (list != null && list.Count > 0)
            {
                entity.ModuleName =
                    list.Find(x => x.Code == entity.Module)?.Name;
                entity.ActionName =
                    list.Find(x => x.Code == entity.Action)?.Name;
            }
            rep_home.AddLog(entity);
        }
        /// <summary>
        /// 获取请求体和响应体
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private (string, string) GetContent(ResultExecutedContext context)
        {
            var req = context.HttpContext.Request;
            string requestContent = req.Method switch
            {
                "GET" => req.QueryString.Value,
                _ => GetPost(req)
            };
            var responseContent = Newtonsoft.Json.JsonConvert.SerializeObject(((ObjectResult)context.Result).Value);
            return (requestContent, responseContent);
        }
        private string GetPost(HttpRequest request)
        {
            request.EnableBuffering();
            request.Body.Position = 0;
            using (var reader = new StreamReader(request.Body,
                Encoding.UTF8, true, 1024, true))
                return reader.ReadToEnd();
        }
        
        /// <summary>
        /// 响应后
        /// </summary>
        /// <param name="context"></param>
        public void OnResultExecuting(ResultExecutingContext context)
        {

        }
    }
}
